<template>
  <pro-layout
    :menus="menus"
    :collapsed="collapsed"
    :mediaQuery="query"
    :isMobile="isMobile"
    :handleMediaQuery="handleMediaQuery"
    :handleCollapse="handleCollapse"
    :i18nRender="i18nRender"
    v-bind="settings"
  >
    <!-- Ads begin
      广告代码 真实项目中请移除
      production remove this Ads
    -->
    <!-- <ads v-if="isProPreviewSite && !collapsed"/> -->
    <!-- Ads end -->

    <!-- 1.0.0+ 版本 pro-layout 提供 API，
          我们推荐使用这种方式进行 LOGO 和 title 自定义
    -->
    <template v-slot:menuHeaderRender>
      <div>
        <img src="@/assets/logo.svg" />
        <h1>{{ title }}</h1>
      </div>
    </template>
    <template v-slot:menuRender>
      <a-menu
        mode="inline"
        theme="dark"
        :openKeys="openKeys"
        @openChange="onOpenChange"
        :defaultSelectedKeys="[$route.path]"
        :inline-collapsed="collapsed"
        @click="menuClick"
      >
        <template v-for="(item, index) in menus">
          <template v-if="!item.hidden">
            <a-sub-menu :key="index" v-if="item.children && item.children.length">
              <template slot="title">
                <icon-font :type="item.meta.icon" />
                <a-badge :dot="item.children.length && item.children.findIndex((chd) => chd.meta.isred === 1) > -1">
                  {{ item.meta.title }}
                </a-badge>
              </template>
              <template v-for="child in item.children">
                <a-menu-item v-if="!child.hidden" :key="child.path">
                  <a-badge :dot="child.meta.isred == 1">
                    {{ child.meta.title }}
                  </a-badge>
                </a-menu-item>
              </template>
            </a-sub-menu>
            <a-menu-item v-else :key="item.path">
              <icon-font :type="item.meta.icon" />
              {{ item.meta.title }}
            </a-menu-item>
          </template>
        </template>
      </a-menu>
    </template>
    <!-- 1.0.0+ 版本 pro-layout 提供 API,
          增加 Header 左侧内容区自定义
    -->
    <template v-slot:headerContentRender>
      <div>
        <a-tooltip title="刷新页面">
          <a-icon type="reload" style="font-size: 18px;cursor: pointer;" @click="reload" />
        </a-tooltip>
      </div>
    </template>

    <!-- <setting-drawer v-if="isDev" :settings="settings" @change="handleSettingChange">
      <div style="margin: 12px 0;">
        This is SettingDrawer custom footer content.
      </div>
    </setting-drawer> -->
    <template v-slot:rightContentRender>
      <right-content :top-menu="settings.layout === 'topmenu'" :is-mobile="isMobile" :theme="settings.theme" />
    </template>
    <!-- custom footer / 自定义Footer -->
    <template v-slot:footerRender>
      <global-footer />
    </template>
    <router-view />
  </pro-layout>
</template>

<script>

import { SettingDrawer, updateTheme } from '@ant-design-vue/pro-layout'
import { i18nRender } from '@/locales'
import { mapState } from 'vuex'
import { CONTENT_WIDTH_TYPE, SIDEBAR_TYPE, TOGGLE_MOBILE_TYPE } from '@/store/mutation-types'

import defaultSettings from '@/config/defaultSettings'
import RightContent from '@/components/GlobalHeader/RightContent'
import GlobalFooter from '@/components/GlobalFooter'
// import Ads from '@/components/Other/CarbonAds'
export default {
  name: 'BasicLayout',
  components: {
    SettingDrawer,
    RightContent,
    GlobalFooter
    // Ads,
  },
  inject: ['reload', 'getMessageNotice'],
  data () {
    return {
      // preview.pro.antdv.com only use.
      // isProPreviewSite: process.env.VUE_APP_PREVIEW === 'true' && process.env.NODE_ENV !== 'development',
      // end
      // isDev: process.env.NODE_ENV === 'development' || process.env.VUE_APP_PREVIEW === 'true',

      // base
      menus: [],
      openKeys: [],
      // 侧栏收起状态
      collapsed: false,
      title: defaultSettings.title,
      settings: {
        // 布局类型
        layout: defaultSettings.layout, // 'sidemenu', 'topmenu'
        // CONTENT_WIDTH_TYPE
        contentWidth: defaultSettings.layout === 'sidemenu' ? CONTENT_WIDTH_TYPE.Fluid : defaultSettings.contentWidth,
        // 主题 'dark' | 'light'
        theme: defaultSettings.navTheme,
        // 主色调
        primaryColor: defaultSettings.primaryColor,
        fixedHeader: defaultSettings.fixedHeader,
        fixSiderbar: defaultSettings.fixSiderbar,
        colorWeak: defaultSettings.colorWeak,

        hideHintAlert: false,
        hideCopyButton: false
      },
      // 媒体查询
      query: {},

      // 是否手机模式
      isMobile: false
    }
  },
  computed: {
    ...mapState({
      // 动态主路由
      mainMenu: state => state.permission.addRouters
    })
  },
  created () {
    const routes = this.mainMenu.find(item => item.path === '/')
    this.menus = (routes && routes.children) || []
    // 处理侧栏收起状态
    this.$watch('collapsed', () => {
      this.$store.commit(SIDEBAR_TYPE, this.collapsed)
    })
    this.$watch('isMobile', () => {
      this.$store.commit(TOGGLE_MOBILE_TYPE, this.isMobile)
    })
    // 将从缓存中取出openKeys
    const openKeys = window.sessionStorage.getItem('openKeys')
    if (openKeys) {
      // 存在即赋值
      this.openKeys = JSON.parse(openKeys)
    }
    this.getMessageNotice()
  },
  mounted () {
    const userAgent = navigator.userAgent
    if (userAgent.indexOf('Edge') > -1) {
      this.$nextTick(() => {
        this.collapsed = !this.collapsed
        setTimeout(() => {
          this.collapsed = !this.collapsed
        }, 16)
      })
    }

    // first update color
    // TIPS: THEME COLOR HANDLER!! PLEASE CHECK THAT!!
    if (process.env.NODE_ENV !== 'production' || process.env.VUE_APP_PREVIEW === 'true') {
      updateTheme(this.settings.primaryColor)
    }
  },
  methods: {

    i18nRender,
    handleMediaQuery (val) {
      this.query = val
      if (this.isMobile && !val['screen-xs']) {
        this.isMobile = false
        return
      }
      if (!this.isMobile && val['screen-xs']) {
        this.isMobile = true
        this.collapsed = false
        this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fluid
        // this.settings.fixSiderbar = false
      }
    },
    handleCollapse (val) {
      this.collapsed = val
    },

    // 点击菜单，路由跳转,注意的是当点击MenuItem才会触发此函数
    menuClick ({ item, key, keyPath }) {
      // 获取到当前的key,并且跳转
      if (keyPath.length === 1) { // 没有二级菜单
        window.sessionStorage.setItem('openKeys', JSON.stringify([]))
        this.openKeys = []
      } else if (keyPath.length === 2) { // 有二级菜单
        const openKeys = [keyPath[1]]
        window.sessionStorage.setItem('openKeys', JSON.stringify(openKeys))
        this.openKeys = openKeys // 只展开当前选中的菜单
      }
      // 如果是进入消息通知页面就不请求
      if (key !== '/message/list') this.getMessageNotice()
      // todo 重新请求菜单数据 更新红点
      // this.$store.dispatch('GenerateRoutes', { token: storage.get(ACCESS_TOKEN) }).then(() => {
      //   console.log('aaa')
      // })
      this.$router.push({
        path: key
      })
    },

    onOpenChange (openKeys) {
      // 将当前打开的父级菜单存入缓存中
      window.sessionStorage.setItem('openKeys', JSON.stringify(openKeys))
      this.openKeys = openKeys
    }
    // handleSettingChange ({ type, value }) {
    //   console.log('type', type, value)
    //   type && (this.settings[type] = value)
    //   switch (type) {
    //     case 'contentWidth':
    //       this.settings[type] = value
    //       break
    //     case 'layout':
    //       if (value === 'sidemenu') {
    //         this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fluid
    //       } else {
    //         this.settings.fixSiderbar = false
    //         this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fixed
    //       }
    //       break
    //   }
    // }
  }
}
</script>

<style lang="less">
@import "./BasicLayout.less";
// html {
//   overflow: hidden;
// }
// #app {
//   height: 100vh;
//   border-top: #f7f7f7 solid 1px;
// }
// .ant-layout-content {
//   height: calc(100vh - 64px);
//   overflow: auto;
//   padding: 24px;
//   margin: 0;
// }

// .ant-layout-sider-children .ant-menu {
//   max-height: calc(100vh - 64px);
//   overflow: auto;
// }

.ant-layout-sider-children .ant-menu::-webkit-scrollbar {
  width: 6px;
  background: #000c17;
}
.ant-layout-sider-children .ant-menu::-webkit-scrollbar-track {
  background: #000c17;
  border-radius: 10px;
}
.ant-layout-sider-children .ant-menu::-webkit-scrollbar-thumb {
  background: #001529;
  border-radius: 10px;
}
.ant-layout-sider-children .ant-badge-dot {
  right: -6px;
}
</style>
